package com.epoint.androidphone.mobileoa.ui.todostandard;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.xmlpull.v1.XmlPullParserException;

import srvSeal.SrvSealUtil;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnMultiChoiceClickListener;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Base64;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver.OnPreDrawListener;
import android.webkit.WebSettings.ZoomDensity;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.dianju.showpdf.DJContentView;
import com.epoint.androidmobile.bizlogic.common.FileDownService;
import com.epoint.androidmobile.bizlogic.todo.model.ActivityInfoModel;
import com.epoint.androidmobile.bizlogic.todo.model.FlowInfoModel;
import com.epoint.androidmobile.bizlogic.todo.model.MaterialInfoModel;
import com.epoint.androidmobile.bizlogic.todo.model.OperationInfoModel;
import com.epoint.androidmobile.bizlogic.todo.task.Handle_GetArchive_Task;
import com.epoint.androidmobile.bizlogic.todo.task.Handle_GetWaitHandleDetail_Done_Task;
import com.epoint.androidmobile.bizlogic.todo.task.Handle_GetWaitHandleDetail_Task;
import com.epoint.androidmobile.core.control.AlertUtil;
import com.epoint.androidmobile.core.phoneutil.PhoneHelp;
import com.epoint.androidmobile.core.string.StringHelp;
import com.epoint.androidmobile.core.xml.XMLUtil;
import com.epoint.androidphone.R;
import com.epoint.androidphone.mobileoa.ui.init.InitView;
import com.epoint.androidphone.mobileoa.ui.superview.SuperPhonePage;

/**
 * @author liyc
 * @time 2013-5-10 下午4:14:02
 * @annomation 待办事宜详细，标准工作流
 */
public class TodoStandardDetailView extends SuperPhonePage {
	private SrvSealUtil core;
	private boolean isListener = true;
	long getHandleGetArchiveTaskID;
	WebView wvZW, wvBZ;
	Button btZw, btBz, btFj;
	List<MaterialInfoModel> mlist = new ArrayList<MaterialInfoModel>();
	List<OperationInfoModel> OperationInfoList = new ArrayList<OperationInfoModel>();
	LinearLayout llNextBtn;
	LinearLayout llPDFContent;
	LinearLayout llWirteOperate;
	public static String savePath = "data/data/%s/files/wstemp.pdf";
	String FileType;
	DJContentView contentView;
	ActivityInfoModel activityInfoModel;
	String MessageItemGuid, todoFlag;

	ImageView ivWrite, ivCx, ivNext, ivPre, ivSave, ivSetting;
	private int state = 0;// 操作状态 0：浏览状态 3：橡皮擦状 4手写

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		savePath = String.format(savePath, PhoneHelp.getPackageName(this));

		File f = new File(savePath);
		if (f.exists()) {
			f.delete();
		}

		addContentViewAndTitle(R.layout.todostandarddetailview, "待办详情");

		ivWrite = (ImageView) findViewById(R.id.ivWrite);
		ivWrite.setOnClickListener(this);
		ivCx = (ImageView) findViewById(R.id.ivCx);
		ivCx.setOnClickListener(this);
		ivNext = (ImageView) findViewById(R.id.ivNext);
		ivPre = (ImageView) findViewById(R.id.ivPre);
		ivNext.setOnClickListener(this);
		ivPre.setOnClickListener(this);
		ivSave = (ImageView) findViewById(R.id.ivSave);
		ivSetting = (ImageView) findViewById(R.id.ivSetting);
		ivSetting.setVisibility(View.GONE);
		ivSave.setVisibility(View.GONE);
		MessageItemGuid = getIntent().getStringExtra("MessageItemGuid");
		todoFlag = getIntent().getStringExtra("todoFlag");
		llWirteOperate = (LinearLayout) findViewById(R.id.llWirteOperate);
		llPDFContent = (LinearLayout) findViewById(R.id.llPDFContent);
		llNextBtn = (LinearLayout) findViewById(R.id.llNextBtn);
		wvZW = (WebView) findViewById(R.id.wvZW);
		wvZW.getSettings().setLoadWithOverviewMode(true);
		wvZW.getSettings().setUseWideViewPort(true);
		wvZW.getSettings().setSupportZoom(true);
		wvZW.getSettings().setDefaultZoom(ZoomDensity.CLOSE);
		getLlContent().setBackgroundResource(R.color.white);
		wvBZ = (WebView) findViewById(R.id.wvBz);

		btZw = (Button) findViewById(R.id.btZw);
		btZw.setOnClickListener(this);
		btBz = (Button) findViewById(R.id.btBz);
		btBz.setOnClickListener(this);
		btFj = (Button) findViewById(R.id.btFj);
		btFj.setOnClickListener(this);

		getData();

		FileType = getIntent().getStringExtra("FileType");

		if (getString(R.string.SupportWriteSign).equals("1")) {
			if (FileType.equals("SW") || FileType.equals("FW")) {
				wvZW.setVisibility(View.GONE);
				llPDFContent.setVisibility(View.VISIBLE);
				getBtRight().setVisibility(View.VISIBLE);
				getBtRight().setText("手写");
			}
		}

	}

	@Override
	public void onClick(View v) {
		super.onClick(v);
		if (v == btFj) {
			if (mlist.size() == 0) {
				return;
			}
			String[] attstr = new String[mlist.size()];
			for (int i = 0; i < mlist.size(); i++) {
				attstr[i] = mlist.get(i).MaterialInstanceName;
			}
			AlertUtil.showAlertMenu(this, "附件下载", attstr,
					new OnClickListener() {

						@Override
						public void onClick(DialogInterface dialog, int which) {
							MaterialInfoModel m = mlist.get(which);
							FileDownService.download(getContext(),
									getString(R.string.WebServiceType),
									m.DownLoadUrl, m.isBigFile,
									MessageItemGuid, m.MaterialInstanceName,
									InitView.attachdownMainPath);
						}
					});
		} else if (v == btZw) {
			wvZW.setVisibility(View.VISIBLE);
			wvBZ.setVisibility(View.GONE);
		} else if (v == btBz) {
			wvZW.setVisibility(View.GONE);
			wvBZ.setVisibility(View.VISIBLE);
		} else if (v == getBtRight()) {/*
										 * String[] steps = new
										 * String[OperationInfoList.size()];
										 * for(int i=0;i<steps.length;i++) {
										 * steps[i] =
										 * OperationInfoList.get(i).OperationName
										 * ; } AlertUtil.showAlertMenu(this,
										 * "操作", steps, new OnClickListener() {
										 * 
										 * @Override public void
										 * onClick(DialogInterface dialog, int
										 * which) {
										 * 
										 * } });
										 */
			if (llWirteOperate.getVisibility() == View.GONE) {
				llWirteOperate.setVisibility(View.VISIBLE);
			} else {
				llWirteOperate.setVisibility(View.GONE);
			}
		} else if (v == ivWrite) {
			setScanOrWrite();
		} else if (v == ivCx) {
			// core.undoAll(core.objID);
			// contentView.forceRedraw();
			state = 0;// 返回浏览状态
			contentView.setCurrAction(0);
			ivWrite.getBackground().setAlpha(0);// 设置透明度
			// ivWrite.setBackgroundColor(Color.BLACK);
			contentView.undoAll(false);
		} else if (v == ivPre) {
			contentView.changePage(-1);
		} else if (v == ivNext) {
			contentView.changePage(+1);
		}
	}

	public void setScanOrWrite() {
		// core.setWrite(!core.isWrite());
		// if (core.isWrite()) {
		// ivWrite.setSelected(true);
		// ivWrite.setBackgroundColor(getResources().getColor(R.color.yellow));
		// } else {
		// ivWrite.setSelected(false);
		// ivWrite.setBackgroundColor(getResources().getColor(
		// R.color.transparent));
		// }
		contentView.setPenProp(6, 250);
		if (state == 0 || state == 3) {
			// 浏览状态或者橡皮擦状态改为手写状态
			state = 4;
			ivWrite.getBackground().setAlpha(255);// 设置透明度
			ivWrite.setBackgroundColor(Color.YELLOW);
			contentView.setCurrAction(4);// 手写状态
		} else if (state == 4) {
			// 手写状态改为浏览状态
			state = 0;
			ivWrite.getBackground().setAlpha(0);// 设置透明度
			contentView.setCurrAction(0);// 手写状态
		}
	}

	private void getData() {
		showTopProgressBar();
		HashMap<String, Object> params = getPassMap();
		params.put("MessageItemGuid", MessageItemGuid);
		// 已办
		if ("1".equals(todoFlag)) {
			getTvTitle().setText("已办详情");
			getHandleGetArchiveTaskID = new Handle_GetWaitHandleDetail_Done_Task(
					this, params).startTask();
			// 待办
		} else {
			getTvTitle().setText("待办详情");
			getHandleGetArchiveTaskID = new Handle_GetWaitHandleDetail_Task(
					this, params).startTask();
		}
	}

	@Override
	public void refreshUI(long taskId, Object obj) {
		super.refreshUI(taskId, obj);
		if (taskId == getHandleGetArchiveTaskID) {
			if (validateXML(obj)) {
				final String bs = obj.toString();
				String MaterialListXML = StringHelp.getXMLAttOut(bs,
						"MaterialList");
				List<MaterialInfoModel> mlistTemp = XMLUtil.DomAnalysisCommon(
						MaterialListXML, MaterialInfoModel.class);
				for (int i = 0; i < mlistTemp.size(); i++) {
					MaterialInfoModel mim = mlistTemp.get(i);
					if (!mim.MaterialType.equals("Form")
							&& !mim.isBigFile.equals("1")) {
						mlist.add(mim);
					}
				}

				if (mlist.size() > 0) {
					btFj.setText("附件(" + mlist.size() + ")");
				}

				String FormShowUrl = StringHelp.getXMLAtt(bs, "FormShowUrl");
				wvZW.loadUrl(FormShowUrl);

				String FlowInfoLstXML = StringHelp.getXMLAttOut(bs,
						"FlowInfoLst");
				List<FlowInfoModel> flowList = XMLUtil.DomAnalysisCommon(
						FlowInfoLstXML, FlowInfoModel.class);
				String bsstr = Handle_GetArchive_Task
						.pingProcessXML_WS(flowList);
				wvBZ.loadDataWithBaseURL(null, bsstr, "text/html", "utf-8",
						null);

				String OperationListXML = StringHelp.getXMLAttOut(bs,
						"OperationList");
				try {
					OperationInfoList = Handle_GetWaitHandleDetail_Task
							.getOperationInfoModelList(OperationListXML);
				} catch (XmlPullParserException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

				for (int i = 0; i < OperationInfoList.size(); i++) {
					final OperationInfoModel oim = OperationInfoList.get(i);
					LayoutInflater mInflater = LayoutInflater
							.from(getContext());
					Button btn = (Button) mInflater.inflate(
							R.layout.todonextbutton, null);
					btn.setText(oim.OperationName);
					btn.setTag(i);

					btn.setOnClickListener(new android.view.View.OnClickListener() {

						@Override
						public void onClick(View v) {

							if (getString(R.string.SupportWriteSign)
									.equals("1")) {
								System.out.println(new File(savePath)
										.getParent());
								File dir = new File(new File(savePath)
										.getParent());
								if (!dir.exists()) {
									dir.mkdirs();
								}
								int returnsave = contentView.saveFile(savePath);
								System.out.println("return save=" + returnsave);
							}

							// 转交
							if ("shift".equals(oim.OperationType)) {
								Intent intent = new Intent(getContext(),
										TodoStandardNextStepView.class);
								intent.putExtra("MessageItemGuid",
										MessageItemGuid);
								intent.putExtra("OperationInfoModel", oim);
								intent.putExtra("activityInfoModel",
										activityInfoModel);
								intent.putExtra("fz30", 0);
								startActivityForResult(intent, 1001);
								// 退回
							} else if ("back".equals(oim.OperationType)) {
								Intent intent = new Intent(getContext(),
										TodoStandardNextStepView.class);
								intent.putExtra("MessageItemGuid",
										MessageItemGuid);
								intent.putExtra("OperationInfoModel", oim);
								intent.putExtra("activityInfoModel",
										activityInfoModel);
								intent.putExtra("fz30", 0);
								startActivityForResult(intent, 1001);
								// 送下一步
							} else if ("pass".equals(oim.OperationType)
									|| "pass_transition"
											.equals(oim.OperationType)) {
								if (activityInfoModel.SplitType.equals("10")) {
									Intent intent = new Intent(getContext(),
											TodoStandardNextStepView.class);
									intent.putExtra("MessageItemGuid",
											MessageItemGuid);
									intent.putExtra("OperationInfoModel", oim);
									intent.putExtra("activityInfoModel",
											activityInfoModel);
									startActivityForResult(intent, 1001);
								} else if (activityInfoModel.SplitType
										.equals("30")) {
									// --------------送批办步骤add by wangzhigang at
									// 2013-07-23
									// 16:35---------------------------

									if ("1".equals(oim.IsSongPY)) {
										Intent intent = new Intent(
												getContext(),
												TodoStandardNextStepView.class);
										intent.putExtra("MessageItemGuid",
												MessageItemGuid);
										intent.putExtra("OperationInfoModel",
												oim);
										intent.putExtra("activityInfoModel",
												activityInfoModel);
										intent.putExtra("fz30", 0);
										startActivityForResult(intent, 1001);
										return;
									}
									// --------------送批办步骤end by wangzhigang at
									// 2013-07-23
									// 16:35---------------------------

									if (oim.TargetActivityList.size() == 1) {
										Intent intent = new Intent(
												getContext(),
												TodoStandardNextStepView.class);
										intent.putExtra("MessageItemGuid",
												MessageItemGuid);
										intent.putExtra("OperationInfoModel",
												oim);
										intent.putExtra("activityInfoModel",
												activityInfoModel);
										intent.putExtra("fz30", 0);
										startActivityForResult(intent, 1001);
										return;
									}
									String[] activityNames = new String[oim.TargetActivityList
											.size()];
									for (int k = 0; k < activityNames.length; k++) {
										activityNames[k] = oim.TargetActivityList
												.get(k).ActivityName;
									}
									AlertUtil.showAlertMenu(getContext(),
											"请选择分支活动", activityNames,
											new OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													Intent intent = new Intent(
															getContext(),
															TodoStandardNextStepView.class);
													intent.putExtra(
															"OperationInfoModel",
															oim);
													intent.putExtra(
															"activityInfoModel",
															activityInfoModel);
													intent.putExtra(
															"MessageItemGuid",
															MessageItemGuid);
													intent.putExtra("fz30",
															which);
													startActivityForResult(
															intent, 1001);
												}
											});
								} else if (activityInfoModel.SplitType
										.equals("20")) {

									String[] activityNames = new String[oim.TargetActivityList
											.size()];
									for (int k = 0; k < activityNames.length; k++) {
										activityNames[k] = oim.TargetActivityList
												.get(k).ActivityName;
									}
									final boolean[] checkflag = new boolean[activityNames.length];
									Builder builder = new AlertDialog.Builder(
											getContext());
									builder.setTitle("请选择分支活动");
									builder.setMultiChoiceItems(activityNames,
											null,
											new OnMultiChoiceClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which,
														boolean isChecked) {
													if (isChecked) {
														checkflag[which] = true;
													} else {
														checkflag[which] = false;
													}
												}
											});
									builder.setPositiveButton("确定",
											new OnClickListener() {
												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {
													List<Integer> clist = new ArrayList<Integer>();
													for (int i = 0; i < checkflag.length; i++) {
														if (checkflag[i]) {
															clist.add(i);
														}
													}

													int[] chooseArray = new int[clist
															.size()];
													for (int i = 0; i < chooseArray.length; i++) {
														chooseArray[i] = clist
																.get(i);
													}
													Intent intent = new Intent(
															getContext(),
															TodoStandardNextStepView.class);
													intent.putExtra(
															"OperationInfoModel",
															oim);
													intent.putExtra(
															"MessageItemGuid",
															MessageItemGuid);
													intent.putExtra(
															"activityInfoModel",
															activityInfoModel);
													intent.putExtra("fz20",
															chooseArray);
													startActivityForResult(
															intent, 1001);
													return;
												}
											});
									builder.setNegativeButton("取消", null);
									AlertDialog dialog = builder.create();
									dialog.show();
								}
							}
						}
					});
					llNextBtn.addView(btn);
				}

				if (getString(R.string.SupportWriteSign).equals("1")) {
					llPDFContent.getViewTreeObserver().addOnPreDrawListener(
							new OnPreDrawListener() {
								public boolean onPreDraw() {
									if (isListener) {
										if (core == null) {
											core = (SrvSealUtil) getLastNonConfigurationInstance();
										}
										if (core == null) {
											try {
												core = new SrvSealUtil();
											} catch (Exception e) {
												return isListener;
											}
										}
										String pdfFileContent = StringHelp
												.getXMLAtt(bs, "PDFFileContent");
										byte[] pdfcontent = Base64.decode(
												pdfFileContent, Base64.DEFAULT);
										System.out.println("PDF大小："
												+ pdfFileContent.length());
										contentView = new DJContentView(
												TodoStandardDetailView.this,
												pdfcontent);
										// core.setWrite(false);
										llPDFContent.addView(contentView);
										isListener = false;
									}
									return true;
								}
							});
				}
				activityInfoModel = new ActivityInfoModel();
				String activityInfoXML = StringHelp.getXMLAtt(bs,
						"ActivityInfo");
				activityInfoModel.ActivityGuid = StringHelp.getXMLAtt(
						activityInfoXML, "ActivityGuid");
				activityInfoModel.ActivityName = StringHelp.getXMLAtt(
						activityInfoXML, "ActivityName");
				activityInfoModel.ActivityDispName = StringHelp.getXMLAtt(
						activityInfoXML, "ActivityDispName");
				activityInfoModel.SplitType = StringHelp.getXMLAtt(
						activityInfoXML, "SplitType");
				activityInfoModel.ApplicationConfig = StringHelp.getXMLAtt(
						activityInfoXML, "ApplicationConfig");
				activityInfoModel.Note = StringHelp.getXMLAtt(activityInfoXML,
						"Note");
			}
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 1001) {
			switch (resultCode) {
			case RESULT_OK:
				finish();
				break;
			default:
				break;
			}
		}
	}
}
